package utils

import (
	"fmt"
	"strings"
	"unicode"
)

// TrimSpaces 去除字符串前后空格
func TrimSpaces(s string) string {
	return strings.TrimSpace(s)
}

// TrimSpacesFromSlice 去除字符串切片中每个元素的前后空格
func TrimSpacesFromSlice(slice []string) []string {
	result := make([]string, len(slice))
	for i, s := range slice {
		result[i] = TrimSpaces(s)
	}
	return result
}

// IsEmpty 检查字符串是否为空
func IsEmpty(s string) bool {
	return len(strings.TrimSpace(s)) == 0
}

// IsNotEmpty 检查字符串是否不为空
func IsNotEmpty(s string) bool {
	return !IsEmpty(s)
}

// ToSnakeCase 转换为蛇形命名
func ToSnakeCase(s string) string {
	var result strings.Builder
	for i, r := range s {
		if unicode.IsUpper(r) && i > 0 {
			result.WriteRune('_')
		}
		result.WriteRune(unicode.ToLower(r))
	}
	return result.String()
}

// ToCamelCase 转换为驼峰命名
func ToCamelCase(s string) string {
	words := strings.Split(s, "_")
	var result strings.Builder

	for i, word := range words {
		if i == 0 {
			result.WriteString(strings.ToLower(word))
		} else {
			result.WriteString(strings.Title(word))
		}
	}

	return result.String()
}

// Truncate 截断字符串
func Truncate(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}
	if maxLen <= 3 {
		return s[:maxLen]
	}
	return s[:maxLen-3] + "..."
}

// PadLeft 左填充字符串
func PadLeft(s string, length int, pad string) string {
	if len(s) >= length {
		return s
	}
	padding := strings.Repeat(pad, (length-len(s))/len(pad)+1)
	return padding[:length-len(s)] + s
}

// PadRight 右填充字符串
func PadRight(s string, length int, pad string) string {
	if len(s) >= length {
		return s
	}
	padding := strings.Repeat(pad, (length-len(s))/len(pad)+1)
	return s + padding[:length-len(s)]
}

// Center 居中字符串
func Center(s string, length int, pad string) string {
	if len(s) >= length {
		return s
	}

	totalPad := length - len(s)
	leftPad := totalPad / 2
	rightPad := totalPad - leftPad

	leftPadding := strings.Repeat(pad, leftPad/len(pad)+1)[:leftPad]
	rightPadding := strings.Repeat(pad, rightPad/len(pad)+1)[:rightPad]

	return leftPadding + s + rightPadding
}

// FormatBytes 格式化字节数
func FormatBytes(bytes int64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}

	div, exp := int64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}

	units := []string{"KB", "MB", "GB", "TB", "PB", "EB"}
	return fmt.Sprintf("%.1f %s", float64(bytes)/float64(div), units[exp])
}
